<?php
/**
 * Created by PhpStorm.
 * User: lizx
 * Date: 2018/1/29
 * Time: 17:09
 */

namespace app\api\service;

use app\api\repository\UserRepository;
use app\common\Model\User;
use app\common\Model\UserBalance;
use app\common\Model\UserOpenid;
use app\common\Server\Redis;
use app\common\Service;
use think\Config;
use think\Db;
use think\exception\ErrorException;

class UserService extends Service
{

    //有效时间（一月）
    const EXPIRE = 2678400;
    //tokenRedis键名
    const PREFIX = 'CACHE:TOKEN:%s';

    /**
     * 登陆或注册
     * @param $input
     * @param string $type
     * @return bool
     */
    public function loginOrregister($input, $type = 'mobile')
    {
        $input['appid'] = Config::get('wx_'.$input['client'].'.app_id');
        Db::startTrans();
        try{
            if($type == 'thirdlogin'){
                $user = $this->{$input['source'] . 'Login'}($input);
                if(!$user){
                    if(!(self::$data['is_reg'] ?? 0)){
                        return false;
                    }
                    return self::$data;
                }
            }else{
                $user = User::get(['mobile' => $input['mobile']]);
                $type = $input['type'];
                //有用户
                if($user){
                    //绑定
                    if($type == 'bind'){
                        if($user->unionid != ''){
                            self::$data['err'] = '801006';
                            return false;
                        }
                        $ubrtn = $this->{$input['source'] . 'Bind'}($input);
                    //解绑
                    }elseif ($type == 'unbind'){
                        $ubrtn = $this->{$input['source'] . 'UnBind'}($user->uid);
                        if(!$ubrtn){
                            return false;
                        }
                    }
                //无用户
                }else{
                    if($type == 'unbind'){
                        self::$data['err'] = '801008';
                        return false;
                    }elseif ($type == 'login'){
                     $info = [
                            'mobile' => $input['mobile'],
                        ];
                        $user = User::create($info);
                        UserBalance::create(['uid' => $user->uid]);
                    }elseif ($type == 'bind'){
                        $user = $this->{$input['source'] . 'Bind'}($input);
                    }
                }
            }
            //用户信息
            $app_name = ($input['app_name'] ?? '') === 'shr' ? 'shr' : '';//如果app_name不为空且不是‘shr’置为空
            $this->createToken($user['uid'],$app_name);
            $user = UserRepository::instance()->userInfo($user->uid,'uid',$input['client']);

            Db::commit();
        }catch (ErrorException $exception){
            Db::rollback();
            return false;
        }
        $user['is_reg'] = 0;
        self::$data = $user;
        return true;
    }

    /**
     * 微信绑定
     * @param $data
     * @return $this|bool
     */
    public function wxBind($data)
    {
        $user = User::get(['mobile' => $data['mobile']]);
        if(empty($user)){
            $info = [
                'mobile' => $data['mobile'],
                'unionid' => $data['unionid']
            ];
            $user = User::create($info);
            UserBalance::create(['uid' => $user->uid]);
        }else{
            $user_model = new User;
            $user = $user_model->save([
                'unionid' => $data['unionid']
            ],[
                'mobile' => $data['mobile'],
            ]);
        }
        $user = User::get(['mobile' => $data['mobile']]);

        //保存openid
        $user_open = UserOpenid::get([
            'uid' => $user->uid,
            'appid' => $data['appid'],
        ]);

        if(empty($user_open)){
            $uortn = UserOpenid::create([
                'uid' => $user->uid,
                'appid' => $data['appid'],
                'openid' => $data['openid']
            ]);
        }else{
            $uortn = UserOpenid::update([
                'openid' => $data['openid']
            ],[
                'uid' => $user->uid,
                'appid' => $data['appid'],
            ]);
        }

        if($user && $uortn) return $user;
        else return false;
    }

    /**
     * 微信登陆
     * @param $data
     * @return bool|null|static
     */
    public function wxLogin($data)
    {
        $user = User::get(['unionid' => $data['unionid']]);

        //如果该用户已绑定 则添加或更新openid
        if($user){
            //保存openid
            $user_open = UserOpenid::get([
                'uid' => $user->uid,
                'appid' => $data['appid'],
            ]);

            if(empty($user_open)){
                $uortn = UserOpenid::create([
                    'uid' => $user->uid,
                    'appid' => $data['appid'],
                    'openid' => $data['openid']
                ]);
            }else{
                $uortn = UserOpenid::update([
                    'openid' => $data['openid']
                ],[
                    'uid' => $user->uid,
                    'appid' => $data['appid'],
                ]);
            }
        }

        if(empty($user)){
            self::$data['openid'] = $data['openid'];
            self::$data['unionid'] = $data['unionid'];
            self::$data['is_reg'] = 1;
            return false;
        }
        return $user;
    }

    /**
     * 微信解绑
     * @param $uid
     * @return bool
     */
    public function wxUnBind($uid)
    {
        $urtn = User::update([
            'unionid' => ''
        ],[
            'uid' => $uid,
        ]);
        $uortn = UserOpenid::update([
            'openid' => ''
        ],[
            'uid' => $uid,
//            'appid' => Config::get('wx_dl.app_id'),
        ]);

        if($urtn && $uortn) return true;
        else return false;
    }

    public function __call($name, $arguments)
    {
        self::$data['err'] = '801009';
        return false;
    }

    /**
     * 生成token
     * @param $uid
     * @return string
     */
    public function createToken($uid,$app_name)
    {
        $str = time() . $uid . rand(1000,9999);
        $token = md5($str);

        $ckey  = $app_name . sprintf(self::PREFIX, $uid);
        $redis = new Redis();
        $hredis = $redis->handler();

        $hredis->setex($ckey, self::EXPIRE, $token);

        $token_expired = date('Y-m-d H:i:s',time() + self::EXPIRE);

        $user_model = new User;
        $user = $user_model->save([
            $app_name . 'access_token' => $token,
            'token_expired' => $token_expired
        ],[
            'uid' => $uid
        ]);
//        User::update([
//        ],[
//        ]);

        if($user){
            return true;
        }else{
            return false;
        }
    }
}